package com.ibm.framework.uts.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 网络工具
 * 
 * @author v_pinzhao
 * 
 */
public abstract class NetUtil {
    /**
     * 获取ip
     * 
     * @return 本地ip列表
     * @throws SocketException 异常
     */
    public static List<String> getAllLocalIP() throws SocketException {
        List<String> localIPs = new ArrayList<String>();
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = allNetInterfaces.nextElement();
            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                ip = addresses.nextElement();
                if (!ip.isLoopbackAddress() && ip instanceof Inet4Address) {
                    localIPs.add(ip.getHostAddress());
                }
            }
        }
        return localIPs;
    }

    /**
     * 获取本地ip，返回获取到的所有本地ip，返回第一个
     * 
     * @return 本地ip
     */
    public static String getLocalIP() {
        try {
            List<String> allIps = getAllLocalIP();
            if (null == allIps || allIps.size() < 1) {
                return "unknown IP";
            } else {
                return allIps.get(0);
            }
        } catch (SocketException se) {
            return "unknown IP";
        }
    }
}
